﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using Zhaoxi.NET6.AuthDemo.Utility;

namespace Zhaoxi.NET6.AuthDemo.Controllers
{
    public class AuthController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        #region UrlToken
        /// <summary>
        /// http://localhost:5726/Auth/Urltoken?UrlToken=eleven-123456
        /// </summary>
        /// <returns></returns>
        //[Authorize]//最基础，凭证有效即可
        //[Authorize(Roles = "User")]
        //[Authorize(Roles = "Admin")]
        //[Authorize(Roles = "Admin,User")]
        //[Authorize(Policy = "AdminPolicy")]//支持自定义 等价于[Authorize(Roles = "Admin")]
        //[Authorize(Policy = "AssertionAdminPolicy")]//支持自定义 等价于[Authorize(Roles = "Admin")]
        [Authorize(Policy = "AssertionStudentReason")]
        public async Task<IActionResult> UrlToken()
        {
            var result = await base.HttpContext.AuthenticateAsync(UrlTokenAuthenticationDefaults.AuthenticationScheme);
            if (result?.Principal == null)
            {
                return new JsonResult(new
                {
                    Result = false,
                    Message = $"认证失败，用户未登录"
                });
            }
            else
            {
                base.HttpContext.User = result.Principal;
                StringBuilder sb = new StringBuilder();
                foreach (var item in base.HttpContext.User.Identities.First().Claims)
                {
                    Console.WriteLine($"InfoGet {item.Type}:{item.Value}");
                    sb.Append($"{item.Type}:{item.Value}");
                }

                return new JsonResult(new
                {
                    Result = true,
                    Message = $"认证成功，用户已登录"
                });
            }
        }
        #endregion
    }
}
